package com.lw.leetcode.str.a;

/**
 * 151. 颠倒字符串中的单词
 * 剑指 Offer 58 - I. 翻转单词顺序
 *
 * @Author liw
 * @Date 2021/4/19 16:16
 * @Version 1.0
 */
public class ReverseWords {

    public static void main(String[] args) {
        ReverseWords test = new ReverseWords();
        String s = test.reverseWords("  hello world!  ");
        System.out.println(s);
    }

    public String reverseWords(String s) {
        s = s.trim();
        if (s.length() < 2) {
            if (" ".equals(s)) {
                return "";
            }
            return s;
        }
        int length = s.length();
        StringBuilder all = new StringBuilder(length);
        StringBuilder sb = new StringBuilder(length);
        for (int i = length - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c == ' ') {
                if (sb.length() != 0) {
                    all.append(sb.reverse());
                    all.append(c);
                    sb = new StringBuilder(length);
                }
            } else {
                sb.append(c);
            }
        }
        if (sb.length() == 0) {
            return all.substring(0, all.length() - 1);
        } else {
            all.append(sb.reverse());
            return all.toString();
        }
    }
}


